package com.sskj.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sskj.api.domain.Role;
import com.sskj.api.exception.LogicException;
import com.sskj.api.mapper.RoleMapper;
import com.sskj.api.service.IRoleService;
import com.sskj.api.service.IUserRoleService;
import com.sskj.api.vo.req.RolePageListReq;
import com.sskj.common.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Slf4j
public class RoleService extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private IUserRoleService userRoleService;

    @Override
    public void add(Role role) {
        LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Role::getName, role.getName());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("角色已存在");
        }
        role.setCreateTime(LocalDateTime.now());
        role.setStatus(1);

        save(role);
    }

    @Override
    public void deleteById(Long id) {
        if (userRoleService.countByRoleId(id) > 0) {
            throw new LogicException("当前角色已绑定用户，中止删除操作");
        }
        removeById(id);
    }

    @Override
    public void update(Role role) {
        LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(Role::getId, role.getId())
                .eq(Role::getName, role.getName());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("角色已存在");
        }
        role.setUpdateTime(LocalDateTime.now());

        updateById(role);
    }

    @Override
    public IPage<Role> pageList(RolePageListReq req) {
        LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Role::getId);

        if (StrUtil.isNotBlank(req.getName())) {
            lambdaQueryWrapper.like(Role::getName, req.getName());
        }
        if (req.getStatus() != null && req.getStatus() >= 0) {
            lambdaQueryWrapper.eq(Role::getStatus, req.getStatus());
        }

        Page<Role> pageConfig = new Page<>(req.getPageNum(), req.getPageSize());
        return page(pageConfig, lambdaQueryWrapper);
    }
}
